package com.hudilao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hudilao.common.BaseContext;
import com.hudilao.common.R;
import com.hudilao.dto.DiningTableDTO;
import com.hudilao.entity.DiningTable;
import com.hudilao.mapper.DiningTableMapper;
import com.hudilao.service.DiningTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class DiningTableController {
    @Autowired
    private DiningTableService diningTableService;

    @Autowired
    private DiningTableMapper diningTableMapper;

    /**
     * 用户选择桌子就餐
     * @param diningTableDTO
     * @return
     */
    @PostMapping("/table")
    @Transactional
    public R<String> chooseTable(@RequestBody DiningTableDTO diningTableDTO){

        //接收桌号，判断桌号合法性
        int tableNumber = diningTableDTO.getTableNumber();
        LambdaQueryWrapper<DiningTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DiningTable::getTableNumber,tableNumber);               //根据桌号查询餐桌
        DiningTable diningTable = diningTableService.getOne(queryWrapper);
        if(diningTable == null){
            return R.error("该餐桌不存在");
        }

        //获取当前顾客id
        Long customerId = BaseContext.getCurrentId();

        //判断该客户是否已选择餐桌
        if(diningTableMapper.getTableByCustomerId(customerId) != null){
            return R.error("该用户已选择餐桌");
        }


        //通过桌号在数据库查询该餐桌查询其状态
        Byte status = diningTableMapper.getStatusByTableNumber(tableNumber);

        if(status == null){
            return R.error("该餐桌不存在");
        }

        //不可用，返回
        if(status == 0){
            return R.error("该餐桌使用中");
        }

        //当前餐桌可用，通过桌号修改状态，绑定顾客
        if(status == 1){
            diningTableMapper.updateStatusByTableNumber(tableNumber);
            diningTableMapper.updateCustomerIdByTableNumber(tableNumber,customerId);
            return R.success("用户选择餐桌成功");
        }

        return R.error("未知错误");
    }

}
